<?php
namespace Api\Controller;
/**
 *	Api注册接口
 *  @author Lwbang
 */
class RegisterController extends TokenController {

	private $model;

	protected function _initialize() {
		parent::_initialize();
		$this -> model = M("User");
	}

	/**
	 * 注册API提交方法
	 * @author Lwbang
	 */

	public function reg() {

		if (IS_AJAX) {
			//检测用户名和邮箱是否已经存在
			$username = I('post.user_username', '', 'strval');
			$email = I('post.user_email', '', 'strval');
			$status = $this -> checkUserAndMail($username, $email);
			//如果status为1那么表示
			if ($status['status'] == 1) {
				//将注册内容写入数据库
				$_POST['user_regtime'] = time();
				//生成注册时间
				$_POST['user_password'] = strToCrypt($_POST['user_password']);
				//给密码加密
				$uid = $this -> model -> add(I('post.'));
				if ($uid) {
					$status = array('status' => 1, 'uid' => $uid, 'username' => I('post.user_username'));
					$this -> ajaxReturn($status);
				}

				$this -> ajaxReturn($status);
			}
		}
		$this -> error('非法请求');
	}

	/**
	 * 判断用户名和邮箱是否已经被注册过
	 * @return Array
	 * @author Lwbang
	 */
	private function checkUserAndMail($username, $email) {
		//查询当前用户名是否查询得到相应的用户
		$dbUserName = $this -> model -> where(array('user_username' => $username)) -> getField('user_username');
		//返回邮箱
		$dbEmail = $this -> model -> where(array('user_email' => $email)) -> getField('user_email');
		//判断用户是否已存在
		if ($username == $dbUserName) {
			$status = array('status' => 0, 'msg' => '用户已存在请更换');
			return $status;
		}
		//判断邮箱是否已经存在
		if ($email == $dbEmail) {
			$status = array('status' => 0, 'msg' => '邮箱已经存在请更换');
			return $status;
		}
		//如果都不存在那么返回一个status=1的数组
		return array('status' => 1);
	}

}
